// Declare File Array

function File (name) {
    this.name = name;
    this.contents = '';
   /* this.getInfo = function() {
        return this.color + ' ' + this.type + ' apple';
    }; */
}
var files = new Array();
var currentFile = new File('');
function getFile(fileName)
{
	for(var file in files)
	{
		if(files[file].name == fileName)
		{
			return files[file];
		}
	}
	return false;
}




function openFile(fileName, lesson)
{
	$.ajax({
	  type: "POST",
	  url: '../get_file',
	  data: { file: fileName,
	  		  lesson: lesson },
	  success: function(response)
	  {
	  	var file =  getFile(fileName);
	  	if(!file)
	  	{
	  		file = new File(fileName);
	  		file.contents = response;
	  		files.push(file);
	  		addFileTab(fileName);
	  	}
	  	else
	  	{
	  		//update file (may not be needed)
	  	}
	  }
	});
}

function setCurrentFile(fileName)
{
	var file = getFile(fileName);
		currentFile =  file;
		editor.setValue(file.contents);
}

function addFileTab( name )
{
	$("#fileTab").prepend("<li> <a  href='#"+ name +"' role='tab' data-toggle='tab'>"+ name +"</a> </li>");
	$('#fileTab li').click(function (e) {
		var fileName = e.toElement.text;
		setCurrentFile(fileName);
		
	})
	$('#fileTab a:first').tab('show')
	var fileName = $('#fileTab a:first')[0].text;
	setCurrentFile(fileName);
}
function openFiles(files, lesson)
{
	for(var file in files)
	{
	    openFile(files[file], lesson);
	}
}

function saveCurrentFile()
{
	while(currentFile.name == '')
	{
		currentFile.name = prompt('What would you like to name the file?');
	}
	$.ajax({
	  type: "POST",
	  url: '../save_file',
	  data: { file: currentFile.name,
	  		  lesson: lesson,
	  		  fileContents: currentFile.contents },
	  success: function(response)
	  {
	  	 var currSrc = $("#previewFrame").attr("src");
		 $("#previewFrame").attr("src", currSrc);
	  }
	});
}
function createFile(fileName)
{

	$.ajax({
	  type: "POST",
	  url: '../create_file',
	  data: { file: fileName,
	  		  lesson: lesson,
	  		  fileContents: ''},
	  success: function(response)
	  {
	  	openFile(fileName, lesson);
	  	$('#addFileModal').modal('hide');
	  }
	});
	
	
}

$(window).bind('keydown', function(event) {
    if (event.ctrlKey || event.metaKey) {
        switch (String.fromCharCode(event.which).toLowerCase()) {
        case 's':
            event.preventDefault();
            saveCurrentFile();
            break;
        }
    }
});

function changePart(part_number)
{
	$("#lessonPartsFrame").attr("src", '../get_lesson_part/' + lesson + '/' + lesson_parts[part_number].file_name);
}
function nextPart()
{
	
	if(current_part < lesson_parts.length - 1)
	{
		
		current_part++;
		console.log(current_part);
		changePart(current_part);
	
	}
}
function lastPart()
{
	if(current_part > 0)
	{
		current_part--;
		changePart(current_part);
	}
}